package kr.couponplay.android.activity.deal;

import java.util.List;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.activity.R;
import kr.couponplay.android.domain.BeanFactory;
import kr.couponplay.android.domain.deal.Deal;
import kr.couponplay.android.domain.deal.Qna;
import kr.couponplay.android.domain.deal.QnaBox;
import kr.couponplay.android.domain.deal.QnaDao;
import kr.couponplay.android.support.DisplayUtils;
import kr.couponplay.android.support.StringUtils;
import kr.couponplay.android.support.ad.AdPlatform;
import kr.couponplay.android.support.ad.AdViewFactory;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class DealDetailActivity extends FragmentActivity {
	private Context mContext = this;
	
	private WebView dealImageView;
	private TextView title;
	private TextView originalPrice;
	private TextView salesPrice;
	private TextView discountRate;
	private TextView nowCount;
	private TextView saleToDate;
	private TextView providerName;
	private TextView categoryName;
	private WebView shopMapImageView;
	private TextView shopMapTitleView;
	
	private TextView joinExplain;
	private Button joinButton;
	private Button detailButton;

	private Deal deal;
	private List<QnaBox> qnaBoxList;
	
	private int windowWidth;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.deal_detail_activity);
		windowWidth = DisplayUtils.widthPixel(this);

		overridePendingTransition(R.anim.slide_in_right, android.R.anim.fade_out);

		getDeal();
		drawAdView();
		getShopMapImage();
		getQnaList();
		drawDealImage();
		drawDealDetail();
		drawBottom();
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	if (deal == null) {
    		getDeal();
    		getShopMapImage();
    		getQnaList();
    	}
    	
    	drawDealImage();
    	drawDealDetail();
    	drawBottom();
    }
    
    public void getDeal() {
		deal = (Deal)getIntent().getSerializableExtra("deal");
    }
    
    public void drawDealImage() {
		if (dealImageView == null) {
			dealImageView = (WebView)findViewById(R.id.deal_image);
			dealImageView.setFocusable(false);
			LayoutParams layoutParams = dealImageView.getLayoutParams();
			layoutParams.width = windowWidth;
			layoutParams.height = (int)(windowWidth * 0.60);
			dealImageView.setLayoutParams(layoutParams);
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append("<html><body style='padding:0;margin:0;'>");
		sb.append("<img src='" + deal.getThumbnailImageUrl2() + "' style='width:100%;padding:0;margin:0' />");
		sb.append("</body></html>");
		dealImageView.loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);		
    }
    
	private void drawDealDetail() {
		if (title == null) {
			title = (TextView) findViewById(R.id.detail_title);
		}
		
		if (originalPrice == null) {
			originalPrice = (TextView) findViewById(R.id.detail_original_price);
		}
		
		if (salesPrice == null) {
			salesPrice = (TextView) findViewById(R.id.detail_sales_price);
		}
		
		if (discountRate == null) {
			discountRate = (TextView) findViewById(R.id.detail_discount_rate);
		}
		
		if (nowCount == null) {
			nowCount = (TextView) findViewById(R.id.detail_now_count);
		}
		
		if (saleToDate == null) {
			saleToDate = (TextView) findViewById(R.id.detail_sale_to_date);
		}
		
		if (providerName == null) {
			providerName = (TextView) findViewById(R.id.detail_provider_name);
		}
		
		if (categoryName == null) {
			categoryName = (TextView) findViewById(R.id.detail_category_name);
		}
		
		title.setText(deal.getTitle());
		originalPrice.setText(DisplayUtils.numFormat(deal.getOriginalPrice()) + "원");
		originalPrice.setPaintFlags(originalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
		salesPrice.setText(DisplayUtils.numFormat(deal.getSalesPrice()) + "원");
		discountRate.setText(deal.getDiscountRate() + "%");
		nowCount.setText(DisplayUtils.numFormat(deal.getNowCount()) + "개");
		saleToDate.setText(DisplayUtils.dateFormat(Long.parseLong(deal.getToDate())) + " 까지");
		providerName.setText(deal.getProvider().getName());
		categoryName.setText(deal.getCategoryName());
	}
	
	private void drawBottom() {
		if (joinExplain == null) {
			joinExplain = (TextView)findViewById(R.id.join_explain);
		}
		
		if (joinButton == null) {
			joinButton = (Button)findViewById(R.id.join_button);
		}
		
		if (detailButton == null) {
			detailButton = (Button)findViewById(R.id.detail_button);
		}		
		
		if (StringUtils.isEmpty(deal.getProvider().getJoinUrl())) {
			joinExplain.setVisibility(View.INVISIBLE);
			joinButton.setVisibility(View.INVISIBLE);
		} else {
			joinExplain.setVisibility(View.VISIBLE);
			joinExplain.setText(deal.getProvider().getName() + "에 회원 가입하면\n바로 2,000 캐쉬 지급");

			joinButton.setVisibility(View.VISIBLE);
			joinButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Uri uri = Uri.parse(deal.getProvider().getJoinUrl());
					startActivity(new Intent(Intent.ACTION_VIEW, uri));
				}
			});
		}
        
        detailButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Uri uri = Uri.parse(deal.getDetailViewUrl());
        		startActivity(new Intent(Intent.ACTION_VIEW, uri));
        	}
        });			
	}

	private void drawQanBox() {
		if (qnaBoxList == null) {
			return;
		}
		
		LinearLayout qnaLayout = (LinearLayout)findViewById(R.id.qna_layout);
		
		for (QnaBox qnaBox : qnaBoxList) {
			LinearLayout.LayoutParams qnaBoxParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			qnaBoxParams.setMargins(0, 0, 0, DisplayUtils.pixelFromDp(this, 5));

			LinearLayout qnaBoxLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_box_layout, null);
			qnaBoxLayout.setLayoutParams(qnaBoxParams);
			
			Qna question = qnaBox.getQuestion();
			LinearLayout questionView = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_question, null);
			TextView qUserView = (TextView) questionView.findViewById(R.id.qna_question_user);
			TextView qContentView = (TextView) questionView.findViewById(R.id.qna_question_content);
			
			qUserView.setText(question.getUserName() + " (" + question.getRegisteDate() + ")");
			qContentView.setText(question.getContent());
			qnaBoxLayout.addView(questionView);
			
			for (Qna answer : qnaBox.getAnswers()) {
				LinearLayout.LayoutParams answerParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
				answerParams.setMargins(DisplayUtils.pixelFromDp(this, 15), DisplayUtils.pixelFromDp(this, 5), 0, 0);
				
				LinearLayout answerView = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_answer, null);
				answerView.setLayoutParams(answerParams);
				
				TextView aUserView = (TextView) answerView.findViewById(R.id.qna_answer_user);
				TextView aContentView = (TextView) answerView.findViewById(R.id.qna_answer_content);
				
				aUserView.setText(answer.getUserName() + " (" + answer.getRegisteDate() + ")");
				aContentView.setText(answer.getContent());
				qnaBoxLayout.addView(answerView);				
			}
			qnaLayout.addView(qnaBoxLayout);
		}
		
		LinearLayout questionMoreView = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.qna_question_more, null);
		qnaLayout.addView(questionMoreView);
	}
	
	private void getShopMapImage() {
		final int height = (int)(DisplayUtils.widthPixel(this) * 0.50);
		shopMapImageView = (WebView) findViewById(R.id.deal_shop_map);
		shopMapImageView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, height));
		shopMapTitleView = (TextView) findViewById(R.id.map_name);

		if (StringUtils.isEmpty(deal.getShopLatitude())) {
			shopMapImageView.setVisibility(View.GONE);
			shopMapTitleView.setVisibility(View.GONE);
			return;
		}
		
		StringBuffer url = new StringBuffer();
		url.append("http://maps.google.com/maps/api/staticmap");
		url.append("?center=" + deal.getShopLatitude() + "," + deal.getShopLongitude());
		url.append("&zoom=16");
		url.append("&size=" + windowWidth + "x" + height);
		url.append("&markers=color:blue%7C" + deal.getShopLatitude() + "," + deal.getShopLongitude());
		url.append("&sensor=false");
		
		StringBuffer sb = new StringBuffer();
		sb.append("<html><body style='padding:0;margin:0;'>");
		sb.append("<img src='" + url + "' style='width:100%;padding:0;margin:0' />");
		sb.append("</body></html>");
		shopMapImageView.loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);			
	}
	
	private void getQnaList() {
		Thread thread = new Thread(new Runnable() {
            public void run() {
            	Message msg = Message.obtain();
            	try {
	            	String providerCode = deal.getProvider().getCode();
	        		String metaId = deal.getMetaId();
	        		msg.obj = BeanFactory.getBean(mContext.getApplicationContext(), QnaDao.class).selectList(deal.getId(), providerCode, metaId);
            	} catch (Exception e) {
            		msg.obj = e;
            	}
            	qnaListHandler.sendMessage(msg);
            }
        });
        thread.start();
	}
	
	@SuppressLint("HandlerLeak") 
	private Handler qnaListHandler = new Handler() {
	    @SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
	    	if (msg.obj instanceof Throwable) {
	    		return;
	    	}
	    	
	    	qnaBoxList = (List<QnaBox>)msg.obj;
	    	drawQanBox();
	    }
	};
	
	AdPlatform adPlatform;
	private void drawAdView() {
		adPlatform = AdViewFactory.getInstance(
				AppContext.isUseAdPlatform(getApplicationContext()), AppContext.getAdPlatformType(getApplicationContext()));
		adPlatform.onCreateAdView(this);
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(android.R.anim.fade_in, R.anim.slide_in_left);
	}
	
	@Override
	public void onDestroy() {
		if (adPlatform != null) {
			adPlatform.onDestroyAdView();
		}
		super.onDestroy();
	}
}
